# _*_ coding: utf-8 _*_
# @Author   : Wei Yue
# @Time     : 2023-05-17 15:46
# @Function : 扩展cruiseDetail的表格 添加P_AC,U_AC,I_AC,fre,cos phi, invPwr, yita_INV,yita_MIS,yita_EDS
import os
import pandas as pd
import numpy as np
from motorCalibration.MotorModel import MotorModelCls
from motorCalibration.motorContanst import *

def extendCruiseDetail(motor,path):
    files = os.listdir(path + '/cruiseDetail/')
    for file in files:
        new_path = os.path.join(path + '/cruiseDetail/' + file)
        print('%s ==> 数据扩展中，请耐心等待' % new_path)
        # 判断一下是否扩展过了扩展过则跳过
        cruiseDf = pd.read_excel(new_path)
        if 'ACpwr' in cruiseDf:
            print('%s 文件已经扩展过，跳过' % file)
            continue
        ##########开始模拟电机，计算AC数据，计算时间较长##############
        outDf = motor.loadCruiseProfile(new_path)
        cruiseDf.insert(loc=7, column='ACpwr', value=outDf['ACpwr'])
        cruiseDf.insert(loc=8, column='U_AC', value=outDf['U_AC'])
        cruiseDf.insert(loc=9, column='I_AC', value=outDf['I_AC'])
        cruiseDf.insert(loc=10, column='FREQUENCY', value=cruiseDf['SPEED'] / 20)
        cruiseDf.insert(loc=11, column='cos(phi)', value=outDf['cos(phi)'])
        cruiseDf.insert(loc=15, column='P_GB', value=np.zeros(len(cruiseDf)))
        # cruise里显示的EFFICIENCY实际是二合一的效率
        cruiseDf.rename(columns={'EFFICIENCY':'eff_MIS'},inplace=True)
        cruiseDf.rename(columns={'EFFICIENCY.1':'eff_GB'},inplace=True)
        cruiseDf.insert(loc=18, column='eff_EDS', value=np.zeros(len(cruiseDf)))
        cruiseDf.insert(loc=20, column='eff_INV', value=np.zeros(len(cruiseDf)))
        cruiseDf.insert(loc=21, column='eff_EM', value=np.zeros(len(cruiseDf)))
        # 进一步整理表格
        for i in range(len(cruiseDf)):
            if cruiseDf.loc[i, 'eff_MIS'] == 0:
                cruiseDf.loc[i, 'eff_MIS'] = 100
            cruiseDf.loc[i, 'P_GB'] = cruiseDf.loc[i, 'TORQUE_OUTPUT'] * cruiseDf.loc[
                i, 'SPEED_OUTPUT'] * 2 * pi / 60 / 1000
            if cruiseDf.loc[i, 'MECHANICAL_POWER'] > 0:
                cruiseDf.loc[i, 'eff_EM'] = cruiseDf.loc[i, 'MECHANICAL_POWER'] / cruiseDf.loc[i, 'ACpwr'] * 100
            elif cruiseDf.loc[i, 'MECHANICAL_POWER'] == 0:
                cruiseDf.loc[i, 'eff_EM'] = 100
            else:
                cruiseDf.loc[i, 'eff_EM'] = cruiseDf.loc[i, 'ACpwr'] / cruiseDf.loc[i, 'MECHANICAL_POWER'] * 100
            if cruiseDf.loc[i, 'eff_EM'] > 100:
                cruiseDf.loc[i, 'eff_EM'] = 100

            cruiseDf.loc[i, 'eff_INV'] = cruiseDf.loc[i, 'eff_MIS'] / cruiseDf.loc[i, 'eff_EM'] * 100
            cruiseDf.loc[i, 'eff_EDS'] = cruiseDf.loc[i, 'eff_MIS'] * cruiseDf.loc[i, 'eff_GB'] / 100

        cruiseDf.to_excel(new_path)
        print('%s ==> 数据扩展完成' % new_path)



if __name__ == '__main__':

    HP26 = MotorModelCls('../excel/motorMap.xlsx', 0.00885, 3, 0.1)
    HP26.loadInvEffMap('./excel/INVmap.xlsx')

    oem ='TEST'
    path = 'C:/Users/Lenovo/Desktop/simulationOutput/' + oem